package org.pvt.gui;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import org.jetbrains.annotations.NotNull;
import org.pvt.R;
import org.pvt.model.Models;
import org.pvt.model.db.DBUtils;

import static org.pvt.gui.UIUtils.startActivityForEvent;

/**
 * @author Pavel Talanov
 */
public final class ExpensesActivity extends ListActivityWithMainMenu {

    private Cursor cursor;
    private long lastId = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expenses);
        setCursorAdapter();
        registerForContextMenu(getListView());
    }

    private void setCursorAdapter() {
        SQLiteDatabase readableDB = DBUtils.getReadableDB(this);
        cursor = readableDB.rawQuery("SELECT * FROM expenses WHERE events_id = ? ORDER BY date ASC",
                new String[]{String.valueOf(getEventId())});
        cursor.moveToFirst();
        setListAdapter(new ExpenseCursorAdapter(this, cursor));
    }

    private void resetCursorAdapter() {
        unsetCursorAdapter();
        setCursorAdapter();
    }

    private void unsetCursorAdapter() {
        cursor.close();
    }

    public void onAddClick(@NotNull View view) {
        startActivityForEvent(AddExpenseActivity.class, getEventId(), this);
    }

    public void onCategoriesClick(@NotNull View view) {
        startActivityForEvent(CategoriesActivity.class, getEventId(), this);
    }

    public void onPeopleClick(@NotNull View view) {
        startActivityForEvent(PeopleActivity.class, getEventId(), this);
    }

    public void onCountBalanceClick(@NotNull View view) {
        startActivityForEvent(BalanceActivity.class, getEventId(), this);
    }

    protected long getEventId() {
        return getIntent().getExtras().getLong(Models.Event.getExtrasName());
    }

    @Override
    public void onResume() {
        super.onResume();
        resetCursorAdapter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unsetCursorAdapter();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.expense_context, menu);
        lastId = ((AdapterView.AdapterContextMenuInfo) menuInfo).id;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.contextMenuCancel) {
            return true;
        }
        if (item.getItemId() == R.id.contextMenuDelete) {
            deleteExpense();
        }
        return true;
    }

    private void deleteExpense() {
        assert lastId >= 0;
        assert !cursor.isAfterLast();
        long expenseId = lastId;
        SQLiteDatabase writableDB = DBUtils.getWritableDB(this);
        writableDB.beginTransaction();
        writableDB.delete(Models.Expense.getTableName(), "_id = ?", new String[]{String.valueOf(expenseId)});
        writableDB.delete(Models.Payment.getTableName(),
                Models.Expense.getTableName() + "_id = ?",
                new String[]{String.valueOf(expenseId)});
        writableDB.setTransactionSuccessful();
        writableDB.endTransaction();
        resetCursorAdapter();
    }


}